//
//  AppMgr.m
//  CarCare
//
//  Created by ileo on 14-9-28.
//  Copyright (c) 2014年 baozun. All rights reserved.
//

#import "ScreenMgr.h"
#import "FirstLoginViewController.h"
#import "LoginViewController.h"

#import "UIViewController+Inject.h"

#import "RefreshMgr.h"

#import "WelcomePageView.h"
#import "CommentHelper.h"
#import "BaseWebViewController.h"

#import "PersonInfoViewController.h"

//#import "DrivesViewController.h"
#import "DrivesTabViewController.h"
#import "CarConditionViewController.h"
#import "NoBindingViewController.h"
#import "HomePageViewController.h"
#import "InsuranceViewController.h"

#import "StartPageView.h"
#import "NetAdvertice.h"

#import "UserHelper.h"
#import "CalendarMgr.h"


#define Debug_BackV_Height (__MAIN_HEIGHT / 2)
#define Debug_Btn_Height (40)


@interface ScreenMgr()<UITabBarControllerDelegate>

@property (nonatomic, strong) UITabBarController *tabBarController;

@property (nonatomic, strong) UINavigationController *homeNC;
@property (nonatomic, strong) UINavigationController *carNC;
@property (nonatomic, strong) UINavigationController *drivesNC;
@property (nonatomic, strong) UINavigationController *userNC;
@property (nonatomic, strong) UINavigationController *insuranceNC;

@property (nonatomic, readonly) UIWindow *window;
@property (nonatomic, readonly) UIViewController *centerVC;

//@property (nonatomic , strong) StartPageView * startPage;

//日志控制台背景view
@property (nonatomic , strong) UIView * debugBackV;
//日志控制台打印textview
@property (nonatomic , strong) UITextView * debugTextV;

@end

@implementation ScreenMgr

IMP_SINGLETON

- (instancetype)init
{
    self = [super init];
    if (self) {
        [UIViewController inject];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateReward) name:REFRESH_REWARD object:nil];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(upDateOrderNoRead) name:REFRESH_ORDERNOREAD object:nil];

    }
    return self;
}

-(void)debugAddMessage:(NSString *)message{
    
    [self.debugTextV setText:[NSString stringWithFormat:@"%@---------%@---------\n%@",([self.debugTextV.text isNotNil] ? [NSString stringWithFormat:@"%@\n",self.debugTextV.text] : @""),[CALENDARMGR dateStrWithDate:[NSDate date] format:yyyy_MM_dd_HH_mm_ss],message]];
    [self.debugTextV scrollRangeToVisible:NSMakeRange(self.debugTextV.text.length, 1)];
    DLog(@"~~~~~%@!!!!!",message);
}

-(void)showDebug{
#ifdef DEBUG
    
//    CGFloat buttonW = 60;
//    __weak __typeof(self) wself = self;
//    UIButton * button = [[[UIButton buttonWithFrame:CGRectMake(__MAIN_WIDTH - buttonW - 20, 80, buttonW, buttonW) title:@"测试" textColor:[UIColor whiteColor] font:FONT_DEFAULT_Light(14) click:^{
//        [UIView animateWithDuration:0.3 animations:^{
//            [wself.debugBackV setHidden:!wself.debugBackV.hidden];
//        }];
//    }] setupOnView:self.window] resetBackgroundColor:[[UIColor blackColor] colorWithAlphaComponent:0.8]];
//    button.layer.cornerRadius = buttonW / 2;
//    button.layer.masksToBounds = YES;
//    [self.window bringSubviewToFront:button];
//    
//    [self.window addSubview:self.debugBackV];
//    
//    [self.debugBackV addSubview:self.debugTextV];
//    
//    [[UIButton buttonWithFrame:CGRectMake(10, self.debugTextV.bottom, __MAIN_WIDTH - 10 * 2, Debug_Btn_Height) title:@"清空" textColor:[Theme wordColor] font:FONT_DEFAULT_Light(14) click:^{
//        wself.debugTextV.text = @"";
//    }] setupOnView:self.debugBackV];

#endif
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void)config{
    [UIViewController configDefaultPreferredStatusBarStyle:UIStatusBarStyleLightContent];
    [UIViewController configNavTitleTextColor:[UIColor whiteColor] font:FONT_DEFAULT_Light(18)];
    [UIViewController configViewControllerGesturePopBack];
    [UIViewController configViewControllerRectEdgeNoneForExtendedLayout];
    [UIViewController configNavButtonTextColor:[UIColor whiteColor] font:FONT_DEFAULT_Light(15)];
    [UIViewController configNavBackgroundColor:[Theme mainColor]];
    [UIViewController configNavBackgroundStyle];
    [UIViewController configBackItemIdentifications:^NSDictionary *{
        return @{BACK_ICON:[BackItemModel modelWithOffsetX:-10 icon:[UIImage imageNamed:@"return_icon"]],
                 BACK_GRAY_ICON:[BackItemModel modelWithOffsetX:-10 icon:[ImageHelper renderImage:[UIImage imageNamed:@"return_icon"] withColor:COLOR_HEXSTRING(@"#a3a3a3")]],
                 BACK_ICON_TITLE:[BackItemModel modelWithOffsetX:-10 icon:[UIImage imageNamed:@"return_icon"] titleOffsetX:-5 titleColor:[UIColor whiteColor] titleFont:FONT_DEFAULT_Light(15)]};
    }];
}

-(void)clear{
    if (_tabBarController) self.tabBarController = nil;
    if (_homeNC) self.homeNC = nil;
    if (_userNC) self.userNC = nil;
    if (_drivesNC) self.drivesNC = nil;
    if (_carNC) self.carNC = nil;
}

-(void)showMainScreen{
    [[RefreshMgr sharedInstance] refresh];
    
    [SYSTEMHELPER readAllNotification];
    [CommentHelper startTime];

    if (self.window.rootViewController != self.tabBarController) {
        self.window.rootViewController = self.tabBarController;
    }
}
#pragma mark - 广告启动页

-(void)startWelcomeScreen
{
//    WelcomePageView * welcomePage = [[WelcomePageView alloc]initWithFrame:CGRectMake(0, 0, __MAIN_WIDTH, __MAIN_HEIGHT)];
    self.window.rootViewController = [[UIViewController alloc] init];
    __weak __typeof(self) wself = self;
    if ([STRING_INT(USERINFO.userID) isNotNil]) {
        __block  StartPageView *startPage = [[StartPageView alloc]init];
        __weak typeof(startPage) wstartPage = startPage;
        startPage.adverticeClick = ^(AdverticePageModel * model)
        {
            [[StatisticsMgr sharedInstance] addClickID:[NSString stringWithFormat:@"%@-%@",APP_START_AD,model.title] description:@"开屏广告启动页"];
            [SCREEN viewController:wself.window.rootViewController presentWebViewControllerWithModel:model close:^{
                [wstartPage removeSelfFromWindow];
            }];
        };
        [self.window addSubview:startPage];

        [NetAdvertice loadAdverticesWithCode:APP_START_AD success:^(NSArray *list) {
            if(list.count > 0 && startPage){
                wstartPage.model = list[0];
            }
        } fail:^{
            
        }];
    }
//    [self.window addSubview:welcomePage];
    
    [NSTimer scheduledTimerWithTimeInterval:10 block:^{
        if([[SystemHelper sharedInstance]loadUpdateDic].count > 0)[wself appUpdate:[[SystemHelper sharedInstance]loadUpdateDic]];
    } repeats:NO];
    
}
//检测更新
- (void)appUpdate:(NSDictionary *)appInfo{
    TipsView *tips = [TipsView upgradeTipsWithTitle:[NSString stringWithFormat:@"新版上线"] lightTitles:@[appInfo[@"tips"]] cancelClick:(![appInfo[@"isForce"] boolValue]) ? (^{
        [AlertMgr dismiss:TYPE_VIEW_ALERT];
    }) : nil];
    [tips addOKButton:@"立即升级" clickOK:^{
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:APP_STORE]];
    }];
    [AlertMgr showView:tips];
}
-(void)changeToLoginScreen{

    FirstLoginViewController *vc = [[FirstLoginViewController alloc] init];

    self.window.rootViewController = vc;
}

-(void)showRightScreen{
    if(USERINFO.isLogin && !USERINFO.isVisiter){
        [UserHelper getUserInfoSuccess:nil fail:nil];
        [SCREEN showMainScreen];
    }else{
        [SCREEN changeToLoginScreen];
    }
    [SCREEN showDebug];
}

#pragma mark - viewcontrollers
-(UITabBarController *)tabBarController{
    if (!_tabBarController) {
        _tabBarController = [[UITabBarController alloc] init];
        _tabBarController.viewControllers = @[
                                              self.homeNC,
                                              self.carNC,
                                              self.drivesNC,
//                                              self.insuranceNC,
                                              self.userNC
                                              ];
        _tabBarController.delegate = self;
        _tabBarController.tabBar.tintColor = COLOR_HEXSTRING(@"37bdd6");
        [[UITabBarItem appearance] setTitleTextAttributes:@{NSFontAttributeName:FONT_DEFAULT_Light(10)} forState:UIControlStateNormal];
    }
    return _tabBarController;
}
- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController
{
    return (viewController != tabBarController.selectedViewController);
}

-(UINavigationController *)homeNC{
    if (!_homeNC) {
        
        HomePageViewController *homeVC = [[HomePageViewController alloc] init];
        UIImage *selected = [ImageNamed(@"tabbar_home_H") imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        homeVC.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"首页" image:ImageNamed(@"tabbar_home") selectedImage:selected];
        homeVC.hidesBottomBarWhenPushed = NO;
        _homeNC = [UINavigationController navigationControllerWithRootViewController:homeVC];
    }
    
    return _homeNC;
}
-(UINavigationController *)userNC{
    if (!_userNC) {
        PersonInfoViewController *vc = [[PersonInfoViewController alloc] initWithTableRefreshType:TYPE_TABLE_REFRESH_NONE];
        UIImage *selected = [ImageNamed(@"tabbar_user_H") imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        vc.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"我的" image:ImageNamed(@"tabbar_user") selectedImage:selected];
        vc.hidesBottomBarWhenPushed = NO;
        _userNC = [UINavigationController navigationControllerWithRootViewController:vc];
    }
    return _userNC;
}
-(UINavigationController *)carNC{
    if (!_carNC) {
        UIViewController * vc;
        if([USERINFO.deviceBindingTime isNotNil])
        {
            vc = [[CarConditionViewController alloc] init];
        }else vc = [[NoBindingViewController alloc] init];
        
//        CarConditionViewController *vc = [[CarConditionViewController alloc] init];
        UIImage *selected = [ImageNamed(@"tabbar_car_H") imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        vc.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"车况" image:ImageNamed(@"tabbar_car") selectedImage:selected];
        vc.hidesBottomBarWhenPushed = NO;
        vc.title = @"车况";
        _carNC = [UINavigationController navigationControllerWithRootViewController:vc];
    }
    return _carNC;
}
-(UINavigationController *)drivesNC{
    if (!_drivesNC) {
        UIViewController * vc;
        if([USERINFO.deviceBindingTime isNotNil])
        {
            vc = [[DrivesTabViewController alloc] init];
        }else vc = [[NoBindingViewController alloc] init];
//        DrivesTabViewController *vc = [[DrivesTabViewController alloc] init];
        UIImage *selected = [ImageNamed(@"tabbar_drives_H") imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        vc.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"行程" image:ImageNamed(@"tabbar_drives") selectedImage:selected];
        vc.hidesBottomBarWhenPushed = NO;
        vc.title = @"行程";
        _drivesNC = [UINavigationController navigationControllerWithRootViewController:vc];
    }
    return _drivesNC;
}
-(UINavigationController *)insuranceNC{
    if (!_insuranceNC) {
        InsuranceViewController *vc = [[InsuranceViewController alloc] initWithTableRefreshType:TYPE_TABLE_REFRESH_PULL_DOWN];
        UIImage *selected = [ImageNamed(@"tabbar_insurance_H") imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        vc.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"保险" image:ImageNamed(@"tabbar_insurance") selectedImage:selected];
        vc.hidesBottomBarWhenPushed = NO;
        vc.title = @"保险";
        _insuranceNC = [UINavigationController navigationControllerWithRootViewController:vc];
    }
    return _insuranceNC;
}
-(UIWindow *)window{
    return [UIApplication sharedApplication].delegate.window;
}
-(UIViewController *)centerVC{
    return self.tabBarController.selectedViewController;
}

#pragma mark - notification
-(void)updateReward{
    NSInteger reward = [RefreshMgr sharedInstance].refreshReward.newReward;
    NSString *show = [NSString stringWithFormat:@"%zd",reward];
    if (reward == 0) {
        show = nil;
    }
    
    if ([show isNotNil]) {
        UIView *maintV;
        for (UIView *view in _tabBarController.tabBar.subviews) {
            if (view.left <= maintV.left) {
                maintV = view;
            }
        }
        [maintV showRemind:YES center:CGPointMake(maintV.boundsCenter.x / 4 + 15, 13)];
        
    }else{
        UIView *maintV;
        for (UIView *view in _tabBarController.tabBar.subviews) {
            if (view.left <= maintV.left) {
                maintV = view;
            }
        }
        [maintV showRemind:NO center:CGPointMake(0, 0)];
    }

}
#pragma mark - 更新是否有未读的订单
- (void)upDateOrderNoRead
{
    NSInteger noReadOrderNum = [RefreshMgr sharedInstance].refreshOrderNoRead.noReadOrderNum;
    NSString *show = [NSString stringWithFormat:@"%zd",noReadOrderNum];
    if (noReadOrderNum == 0) {
        show = nil;
    }
    
    if ([show isNotNil]) {
        UIView *maintV;
        for (UIView *view in _tabBarController.tabBar.subviews) {
            if (view.left > maintV.left) {
                maintV = view;
            }
        }
        [maintV showRemind:YES center:CGPointMake(maintV.boundsCenter.x + 13, 10)];
        
    }else{
        UIView *maintV;
        for (UIView *view in _tabBarController.tabBar.subviews) {
            if (view.left > maintV.left) {
                maintV = view;
            }
        }
        [maintV showRemind:NO center:CGPointMake(0, 0)];
    }
}

- (void)changePageToWay
{
    [self.tabBarController setSelectedIndex:2];
    [(DrivesTabViewController *)self.drivesNC.visibleViewController showTodayData];
}

#pragma mark - 
-(void)viewController:(UIViewController *)viewController presentWebViewControllerWithModel:(AdverticePageModel *)model close:(void (^)())close{
    BaseWebViewController *webVC = [self webViewControllerWithModel:model];
    [webVC navSetupLeftTitle:@"关闭" action:^{
        [webVC dismissViewControllerAnimated:YES completion:nil];
        if (close) close();
    }];
    [viewController presentViewController:[UINavigationController navigationControllerWithRootViewController:webVC] animated:YES completion:nil];
}

-(void)viewController:(UIViewController *)viewController pushWebViewControllerWithModel:(AdverticePageModel *)model{
    [viewController.navigationController pushViewController:[[self webViewControllerWithModel:model] navSetupBackItemWithIdentification:BACK_ICON] animated:YES];
}

-(BaseWebViewController *)webViewControllerWithModel:(AdverticePageModel *)model{
    BaseWebViewController *webVC = [[BaseWebViewController alloc] initWithURL:model.h5URL];
    webVC.title = model.title;
    return webVC;
}
- (UIView *)debugBackV
{
    if(!_debugBackV)
    {
        _debugBackV = [[UIView viewWithFrame:CGRectMake(0, __MAIN_HEIGHT / 2, __MAIN_WIDTH, Debug_BackV_Height)] resetBackgroundColor:[Theme mainNavColor]];
        [_debugBackV setHidden:YES];
    }
    return _debugBackV;
}
- (UITextView *)debugTextV
{
    if (!_debugTextV) {
        CGFloat top = 10;
        _debugTextV = [[UITextView alloc] initWithFrame:CGRectMake(top, top, __MAIN_WIDTH - top * 2, Debug_BackV_Height - top - Debug_Btn_Height)];
    }
    return _debugTextV;
}

#pragma mark - 客服

//-(UIViewController *)currentViewController{
//    return self.currentViewController;
//}



@end
